<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="编辑部件"
    :destroy-on-close="true"
    @ok="handleSubmit"
    ok-text="保存"
  >
    <BasicForm @register="registerForm">
      <template #upload>
        <Upload
          v-model:fileList="fileList"
          accept=".jpg,.png,.gif,.svg,.bmp,.jpeg,.webp,.ico"
          :maxCount="1"
          :beforeUpload="handleBeforeUpload"
          listType="picture"
          @remove="handleRemove"
        >
          <a-button> 选择图片 </a-button>
        </Upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { Upload } from 'ant-design-vue';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  import { editModalSchema } from './editModal.data';
  import { ref } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { getWidgetById } from '/@/api/thingsborad/resources/widgets/widgets';

  const emit = defineEmits(['success']);
  const fileList = ref<any[]>();
  const image = ref<any>();
  const mode = ref<string>();
  const record = ref<any>();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: true });
    mode.value = data.key;
    record.value = cloneDeep(data.record);
    setFieldsValue({ ...record.value, tags: record.value.tags ? record.value.tags : undefined });
    record.value.image && (fileList.value = [{ url: record.value.image }]);
    const { descriptor, externalId } = await getWidgetById(record.value.id);
    record.value.descriptor = descriptor;
    record.value.externalId = externalId;
    setModalProps({ confirmLoading: false });
  });
  const [registerForm, { validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas: editModalSchema,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const handleBeforeUpload = (file: File) => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = async (e) => {
      image.value = e.target?.result;
    };
    return false;
  };

  // 删除图片事件
  const handleRemove = () => {
    image.value = null;
    return true;
  };

  const handleSubmit = async () => {
    try {
      const values = await validate();
      values.image = image.value;
      record.value && Object.assign(record.value, values);
      record.value.id = {
        entityType: 'WIDGET_TYPE',
        id: record.value.id,
      };
      delete record.value.widgetType;
      closeModal();
      emit('success', mode.value, { record: record.value });
    } catch (error) {}
  };
</script>
